//
//  MDSlideTitleView.swift
//  麦兜直播
//
//  Created by yeqingyu on 16/9/25.
//  Copyright © 2016年 yeqingyu. All rights reserved.
//

private let kNormalColor : (CGFloat, CGFloat, CGFloat) = (147, 143, 150)
private let kSelectColor : (CGFloat, CGFloat, CGFloat) = (228, 127, 29)


import UIKit

protocol MDSlideTitleViewDelegate:class {
    func MDSlideTitleViewDidClickTitle(_ currentIndex:Int)
}

class MDSlideTitleView: UIView {
    var titles:[String]
    var line :UIView?
    var oldCell:MDSlideTitleCell?
    var titleCollectView:UICollectionView?
    
    weak  var delegate:MDSlideTitleViewDelegate?
    
     init(frame: CGRect,titles:[String]) {
        self.titles = titles
    
        super.init(frame: frame)
        addSubview(UIView())
        setUpHeadView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension MDSlideTitleView{

   fileprivate func setUpHeadView() {
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .horizontal
    layout.minimumLineSpacing = 0
    layout.minimumInteritemSpacing = 0
    let itemW = bounds.size.width/CGFloat(self.titles.count)
    layout.itemSize = CGSize(width: itemW, height: bounds.size.height)
    let titleCollectView = UICollectionView(frame: bounds, collectionViewLayout: layout)
    titleCollectView.backgroundColor = UIColor.white
    self.titleCollectView = titleCollectView
    titleCollectView.dataSource = self
    titleCollectView.delegate = self
    titleCollectView.register(UINib(nibName: "MDSlideTitleCell", bundle: nil), forCellWithReuseIdentifier: "title_cell")
    self.addSubview(titleCollectView)
    setUpLine(itemW)
    
    }
    

  fileprivate func setUpLine(_ width:CGFloat) {
        let line  = UIView(frame: CGRect(x: 0, y: bounds.size.height-2, width: width, height: 2))
        line.backgroundColor = UIColor(r:kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2, a: 1)
        self.line = line
        addSubview(line)
    }
    

    // MARK:- 设置头部分界线的偏移
    func setUpLineOffSetWithAnimation(_ startPoint:CGPoint,offset:CGPoint) {
        
        
        let scale = offset.x/(CGFloat(self.titles.count)*screenWidth)
        let offX = scale*screenWidth
        UIView.animate(withDuration: animationDuration) {
         self.line?.frame.origin.x = offX
        }
        
        // 1.定义获取需要的数据
        var progress : CGFloat = 0
        var sourceIndex : Int = 0
        var targetIndex : Int = 0
        
        // 2.判断是左滑还是右滑
        let currentOffsetX = offset.x
        let scrollViewW = screenWidth
        let startOffsetX = startPoint.x
        
        if currentOffsetX > startOffsetX { // 左滑
            // 1.计算progress
            progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)
            
            // 2.计算sourceIndex
            sourceIndex = Int(currentOffsetX / scrollViewW)
            
            // 3.计算targetIndex
            targetIndex = sourceIndex + 1
            if targetIndex >= titles.count {
                targetIndex = titles.count - 1
            }
            
            // 4.如果完全划过去
            if currentOffsetX - startOffsetX == scrollViewW {
                progress = 1
                targetIndex = sourceIndex
            }
        } else { // 右滑
            // 1.计算progress
            progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW))
            
            // 2.计算targetIndex
            targetIndex = Int(currentOffsetX / scrollViewW)
            
            // 3.计算sourceIndex
            sourceIndex = targetIndex + 1
            if sourceIndex >= titles.count {
                sourceIndex = titles.count - 1
            }
        }
        let currentIndexPath = IndexPath(row: sourceIndex, section: 0)
        let nextIndexPath = IndexPath(row: targetIndex, section: 0)
        let currentCell:MDSlideTitleCell = titleCollectView?.cellForItem(at: currentIndexPath as IndexPath) as! MDSlideTitleCell
        let nextCell = titleCollectView?.cellForItem(at: nextIndexPath as IndexPath) as! MDSlideTitleCell
        oldCell = nextCell
        
        let diffColorValue:(CGFloat,CGFloat,CGFloat) = (kSelectColor.0-kNormalColor.0,kSelectColor.1-kNormalColor.1,kSelectColor.2-kNormalColor.2)
        
        // 3.2.变化sourceLabel
        currentCell.headTitle.textColor = UIColor(r: kSelectColor.0 - diffColorValue.0 * progress, g: kSelectColor.1 - diffColorValue.1 * progress, b: kSelectColor.2 - diffColorValue.2 * progress,a:1)
        
        // 3.2.变化targetLabel
        nextCell.headTitle.textColor = UIColor(r: kNormalColor.0 + diffColorValue.0 * progress, g: kNormalColor.1 + diffColorValue.1 * progress, b: kNormalColor.2 + diffColorValue.2 * progress,a:1)

    }
}


extension MDSlideTitleView:UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 4
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell:MDSlideTitleCell = collectionView.dequeueReusableCell(withReuseIdentifier: "title_cell", for: indexPath) as! MDSlideTitleCell
        
        cell.headTitle.text  =  self.titles[indexPath.row]
   
        cell.headTitle.textColor = indexPath.row==0 ? UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2, a: 1) : UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2,a:1.0)
        let indexPath = IndexPath(row: 0, section: 0)
        
        oldCell = collectionView.cellForItem(at: indexPath as IndexPath) as! MDSlideTitleCell?
        return cell

    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        setUpLinePositionForAnimation(indexPath)
        let cell = collectionView.cellForItem(at: indexPath) as! MDSlideTitleCell
        cell.headTitle.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2, a: 1)
        oldCell?.headTitle.textColor = (oldCell?.isSelected)! ? UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2, a: 1) : UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2,a:1.0)
        delegate?.MDSlideTitleViewDidClickTitle(indexPath.row)
        oldCell = cell
    }
    
    
   fileprivate func setUpLinePositionForAnimation(_ indexPath: IndexPath) {
    guard let line = line else {
        return
    }
    let lineX = CGFloat(indexPath.row)*line.bounds.size.width

    UIView.animate(withDuration: animationDuration) {
       line.frame.origin.x = lineX
    }
    
    }
}
